#!/bin/sh

#############################################
#		final.sh Handle the final job       #
#############################################

source ./sefunctions.sh
lfndir="/biomed/user/d/dttung/panam"

chmod a+x *.sh
chmod a+x *.pl

workflow=$1
declare -a listfiles=`./pnls.sh outputs | grep $workflow/alnphy`
# Verify if there is the file final.tar.gz under $lfndir
# If YES, that means other 'final' jobs has done and has results
finalverify=`./pnls.sh outputs $workflow | grep "final"`
if [ -n "$finalverify" ]; then # File has been uploaded
	echo "File final.tar.gz has been uploaded by other 'final' job"
	exit 0;
fi

# Download results from alnphy jobs
for alnphy in ${listfiles[@]}
do
	echo "Download $alnphy ..."
	dirac-dms-get-file $alnphy
	if [ $? -eq 0 ]; then
		echo "Done!"
		zarfile=`echo $alnphy | cut -d"/" -f9`
		tar -xzf $zarfile # => results/panam_output
	else
		echo "Error downloading $alnphy"
		exit 1
	fi
done

echo -ne "Check preprocess.tar.gz ... "
if [ ! -f preprocess.tar.gz ]; then
	echo "File preprocess.tar.gz is not existed!"
	exit 1;
fi
# Download preprocess.tar.gz (which includes results/preprocess_output needed by final.pl)
#dirac-dms-get-file "$lfndir/outputs/$workflow/preprocess.tar.gz"
#if [ $? -eq 0 ]; then
#	echo "Done!"
#	tar -xzf preprocess.tar.gz
#else
#	echo "Error downloading preprocess.tar.gz"
#	exit 1
#fi

#### no need $workflow-pre.tar.gz because now test/barcode.txt is included in preprocess.tar.gz

# Download $workflow-pre.tar.gz (which includes test/* needed by final.pl)
# dirac-dms-get-file "$lfndir/inputs/$workflow-pre.tar.gz"
# if [ $? -eq 0 ]; then
#	echo "Done!"
#	tar -xzf $workflow-pre.tar.gz
#else#
#	echo "Error downloading $workflow-pre.tar.gz"
#	exit 1
#fi

echo "All downloaded, now run final.pl"
# Run final.pl
./final.pl

# Prepare results
mkdir final
mv results/*.txt final
mv results/panam_output/*.txt final

tar -czf final.tar.gz final

# Verify if there is the file final.tar.gz under $lfndir
# If YES, that means other 'final' jobs has done and has results
finalverify=`./pnls.sh outputs $workflow | grep "final"`
if [ -n "$finalverify" ]; then # File has been uploaded
	echo "File final.tar.gz has been uploaded by other 'final' job"
	exit 0;
fi

echo -ne "Copy final results to grid ... "
CopyToGrid $lfndir/outputs/$workflow final.tar.gz 0 copyfinal.log
echo "Done"

